<template>
  <div class="image-resource">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <span class="title">图片资源管理</span>
            <!-- 批量操作按钮组 -->
            <div class="batch-operations">
              <el-button-group>
                <el-button @click="handleSelectAll">全选</el-button>
                <el-button @click="handleInvertSelection">反选</el-button>
                <el-button @click="handleClearSelection">清空</el-button>
              </el-button-group>
              <el-button
                  type="danger"
                  v-if="selectedImages.length > 0"
                  @click="handleBatchDelete"
              >
                批量删除({{ selectedImages.length }})
              </el-button>
              <!-- 添加清空所有图片的按钮 -->
              <el-button
                  type="danger"
                  @click="handleClearAll"
              >
                清空所有图片
              </el-button>
              <!-- 添加清空所有图片的按钮 -->
              <el-button
                  type="danger"
                  @click="clearAll"
              >
                立即触发
              </el-button>
            </div>
          </div>
          <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :http-request="customUpload"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              multiple
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="图片来源" style="width: 220px">
            <el-select v-model="searchForm.type" placeholder="请选择来源" clearable>
              <el-option label="管理员上传" value="ADMIN"/>
              <el-option label="爬虫抓取" value="CRAWLER"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 图片展示区域 -->
      <div class="image-list" v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in imageList" :key="item.id">
            <el-card
                :body-style="{ padding: '10px' }"
                class="image-card"
            >
              <div class="image-select">
                <el-checkbox v-model="selectedImages" :label="item.id" />
              </div>

              <el-image
                  :src="item.url"
                  fit="cover"
                  :preview-src-list="[item.url]"
                  class="image"
              />
              <div class="image-info">
                <div class="filename" :title="item.originalName">
                  {{ item.originalName }}
                </div>
                <div class="stats">
                  <span>{{ formatSize(item.size) }}</span>
                  <el-tag size="small" :type="item.type === 'ADMIN' ? '' : 'warning'">
                    {{ item.type === 'ADMIN' ? '管理员' : '爬虫' }}
                  </el-tag>
                </div>
                <div class="time">{{ formatDate(item.createTime) }}</div>
                <div class="operations">
                  <el-button link type="primary" @click="copyUrl(item)">
                    复制链接
                  </el-button>
                  <el-button link type="danger" @click="handleDelete(item)">
                    删除
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="page.current"
            v-model:page-size="page.size"
            :total="page.total"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getImageList, deleteImage, batchDeleteImages, clearAllImages, triggerCleanup} from '@/api/image'
import { formatDate } from '@/utils/date'
import { useConfigStore } from '@/stores/sysConfig.js'
import { uploadOSS } from '@/api/upload'

const configStore = useConfigStore()
const loading = ref(false)
const imageList = ref([])
// 选中的图片
const selectedImages = ref([])

const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)

    const response = await uploadOSS(formData)

    if (response.code === 200) {
      handleUploadSuccess(response)
      options.onSuccess(response)
    } else {
      options.onError(new Error('Upload failed'))
      ElMessage.error('上传失败')
    }
  } catch (error) {
    options.onError(error)
    ElMessage.error('上传失败')
  }
}

const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    ElMessage.success('上传成功')
    loadImageList()  // 刷新列表
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 全选
const handleSelectAll = () => {
  selectedImages.value = imageList.value.map(item => item.id)
}

// 反选
const handleInvertSelection = () => {
  const allIds = imageList.value.map(item => item.id)
  selectedImages.value = allIds.filter(id => !selectedImages.value.includes(id))
}

// 清空选择
const handleClearSelection = () => {
  selectedImages.value = []
}

const clearAll = () => {
  triggerCleanup().then((res) => {
    ElMessage.success('磁盘已清空')
    loadImageList() // 刷新列表
  }).catch((err) => {
    ElMessage.error('清空失败')
  })
}

// 添加清空所有图片的方法
const handleClearAll = () => {
  ElMessageBox.confirm(
      '此操作将清空所有图片，是否继续？',
      '警告',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
        // 添加二次确认
        distinguishCancelAndClose: true,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '清空中...'

            clearAllImages()
                .then(() => {
                  ElMessage.success('所有图片已清空')
                  loadImageList() // 刷新列表
                  done()
                })
                .catch(() => {
                  ElMessage.error('清空失败')
                })
                .finally(() => {
                  instance.confirmButtonLoading = false
                })
          } else {
            done()
          }
        }
      }
  ).catch(() => {
    ElMessage.info('已取消清空操作')
  })
}


// 切换选择
const toggleSelect = (item) => {
  const index = selectedImages.value.indexOf(item.id)
  if (index === -1) {
    selectedImages.value.push(item.id)
  } else {
    selectedImages.value.splice(index, 1)
  }
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedImages.value.length === 0) {
    ElMessage.warning('请选择要删除的图片')
    return
  }

  ElMessageBox.confirm(
      `确定要删除选中的 ${selectedImages.value.length} 张图片吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await batchDeleteImages(selectedImages.value)
      ElMessage.success('删除成功')
      selectedImages.value = []
      loadImageList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 预览图片
const previewImage = (item) => {
  // 如果在选择模式下，则切换选择状态
  if (selectedImages.value.length > 0) {
    toggleSelect(item)
  }
}

// 重置选择
const resetSelection = () => {
  selectedImages.value = []
}

// 分页信息
const page = reactive({
  current: 1,
  size: 12,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  type: ''
})

// 加载图片列表
const loadImageList = async () => {
  loading.value = true
  try {
    const data = await getImageList({
      page: page.current,
      size: page.size,
      type: searchForm.type
    })
    imageList.value = data.data.records
    page.total = data.data.total
  } catch (error) {
    ElMessage.error('获取图片列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化文件大小
const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

// 复制图片链接
const copyUrl = (image) => {
  navigator.clipboard.writeText(image.url).then(() => {
    ElMessage.success('链接已复制')
  })
}

// 删除图片
const handleDelete = (image) => {
  ElMessageBox.confirm('确定要删除这张图片吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteImage(image.id)
      ElMessage.success('删除成功')
      loadImageList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 上传相关
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 搜索和重置
const handleSearch = () => {
  resetSelection()
  page.current = 1
  loadImageList()
}

const resetSearch = () => {
  searchForm.type = ''
  handleSearch()
}

// 分页操作
const handleSizeChange = (val) => {
  resetSelection()
  page.size = val
  loadImageList()
}

const handleCurrentChange = (val) => {
  resetSelection()
  page.current = val
  loadImageList()
}

onMounted(async () => {
  await loadImageList()
})
</script>

<style scoped>
/* 添加一些样式调整 */
.el-button--danger.is-plain {
  margin-left: 16px;
}

.card-header .left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.batch-operations {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selected-count {
  color: #409EFF;
  font-weight: 500;
}

.image-card {
  position: relative;
}

.select-overlay {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
  display: none;
  background: rgba(255, 255, 255, 0.8);
  padding: 5px;
  border-radius: 4px;
}

.image-card:hover .select-overlay,
.image-card.is-selected .select-overlay {
  display: block;
}

.image-card.is-selected {
  border: 2px solid #409EFF;
}

.image-card.is-selected::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(64, 158, 255, 0.1);
  pointer-events: none;
}

.image-resource {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.image-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.image-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image {
  height: 200px;
  width: 100%;
  object-fit: cover;
}

.image-info {
  margin-top: 10px;
}

.filename {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 5px;
}

.stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.time {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.operations {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.search-area {
  margin-bottom: 20px;
}
</style>